package com.zjb.demo.system.controller;

import cn.hutool.core.util.ArrayUtil;
import com.mybatisflex.core.paginate.Page;
import com.zjb.demo.common.constant.UserConstants;
import com.zjb.demo.common.domain.response.AjaxResult;
import com.zjb.demo.system.domain.SysDept;
import com.zjb.demo.system.domain.query.SysDeptQuery;
import com.zjb.demo.system.service.SysDeptService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.noear.solon.annotation.*;
import org.noear.solon.validation.annotation.Valid;

import java.util.Comparator;
import java.util.List;

/**
 * 部门信息
 *
 * @author 庄佳彬
 * @since 2023/12/27 21:59
 */
@Valid
@Controller
@Mapping("/system/dept")
@Api(tags = "部门信息")
public class SysDeptController {
    @Inject
    public SysDeptService service;

    @Get
    @Mapping("/list")
    @ApiOperation(value = "部门列表")
    public AjaxResult<Page<SysDept>> list(SysDeptQuery query) {
        return AjaxResult.success(service.pageList(query));
    }

    @Get
    @Mapping("/list/exclude/{deptId}")
    @ApiOperation("查询部门列表（排除节点）")
    public AjaxResult<List<SysDept>> excludeChild(Long deptId) {
        var list = service.list()
                .parallelStream()
                .filter(d -> !d.getDeptId().equals(deptId) && !ArrayUtil.contains(d.getAncestors().split(","), String.valueOf(deptId)))
                .sorted((Comparator.comparingLong(SysDept::getParentId).thenComparingInt(SysDept::getOrderNum)))
                .toList();
        return AjaxResult.success(list);
    }

    @Get
    @Mapping("/{deptId}")
    @ApiOperation(value = "根据部门编号获取详细信息")
    public AjaxResult<SysDept> detail(Long deptId) {
        service.checkDeptDataScope(deptId);
        return AjaxResult.success(service.getById(deptId));
    }

    @Post
    @Mapping
    @ApiOperation(value = "保存部门信息")
    public AjaxResult<Boolean> save(@Body SysDept sysDept) {
        if (service.checkDeptNameUnique(sysDept)) {
            return AjaxResult.fail("新增部门'" + sysDept.getDeptName() + "'失败，部门名称已存在");
        }
        return AjaxResult.success(service.save(sysDept));
    }

    @Put
    @Mapping
    @ApiOperation(value = "修改部门信息")
    public AjaxResult<Boolean> update(@Body SysDept sysDept) {
        var deptId = sysDept.getDeptId();
        service.checkDeptDataScope(deptId);
        if (service.checkDeptNameUnique(sysDept)) {
            return AjaxResult.fail("修改部门'" + sysDept.getDeptName() + "'失败，部门名称已存在");
        } else if (deptId.equals(sysDept.getParentId())) {
            return AjaxResult.fail("修改部门'" + sysDept.getDeptName() + "'失败，上级部门不能是自己");
        } else if (UserConstants.DEPT_DISABLE.equals(sysDept.getStatus()) && service.selectNormalChildrenDeptById(deptId) > 0) {
            return AjaxResult.fail("该部门包含未停用的子部门！");
        }
        return AjaxResult.success(service.updateById(sysDept));
    }

    @Delete
    @Mapping("/{deptId}")
    @ApiOperation(value = "删除部门信息")
    public AjaxResult<Boolean> delete(Long deptId) {
        if (service.hasChildByDeptId(deptId)) {
            return AjaxResult.fail("存在下级部门,不允许删除");
        }
        if (service.checkDeptExistUser(deptId)) {
            return AjaxResult.fail("部门存在用户,不允许删除");
        }
        return AjaxResult.success(service.removeById(deptId));
    }
}
